package com.sh.web.interceptors;

import com.google.gson.Gson;
import com.sh.bean.Resfood;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
//@Component
public class DetailCountInterceptor implements HandlerInterceptor {


    private final RedisTemplate<String, Object> redisTemplate;

    public DetailCountInterceptor(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
        log.info("拦截器启动！！！！！！！！！！！！");
        String parameterValue = null;
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            String path = request.getRequestURI();
            // 假设路径格式固定为 /resfood/findById/{id}
            String[] pathSegments = path.split("/");
            if (pathSegments.length > 3 && "findById".equals(pathSegments[2])) {
                parameterValue = pathSegments[3];
                System.out.println("拦截到的参数值：" + parameterValue);
            }
        }
        redisTemplate.opsForValue().increment("detail_count:" + Integer.parseInt(parameterValue));
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
